/**@file    system.c
 * @brief
 * 
 * @author SealedGhost
 */
 

#include "system.h" 
#include "usart.h"
#include "config.h"
#include "stm32f10x.h"

#include <stdio.h>



#ifdef USE_UCOS
	#include "os_cfg.h"
#endif


#ifdef USE_FREERTOS
	#include "FreeRTOS.h"	
#endif

#ifdef USE_DELAY
static volatile uint32_t CurrSystemTickCnt  = 0;


/**@brief 延时 1 毫秒
 * 
 *
 * @param
 * @return
 * @note
 */
void delayMs(uint32_t ms)
{
//	uint16_t i  = 0;
//	for(; i < ms; i++)
//	{
//		delayUs(1000);
//	}
	
	
	uint32_t targetTick  = CurrSystemTickCnt + ms;
	
	while(CurrSystemTickCnt != targetTick);
}


/**@brief 延时 1 微秒
 * 
 *
 * @param
 * @return
 * @note
 */
void delayUs(uint32_t us)
{
	uint32_t targetTick  = CurrSystemTickCnt + us;
	
	while(CurrSystemTickCnt != targetTick);
}



/**@brief 滴答计数
 * 
 *
 * @param
 * @return
 * @note
 */
void onSystemTick()
{
	CurrSystemTickCnt++;
}
#endif



inline uint32_t getSystemTick(void)
{
	return CurrSystemTickCnt;
}



/**@brief  配置系统滴答时钟频率
 * 
* 在ucOS环境下配置为 OS_TICKS_PER_SEC，在裸机环境下配置为 ticksPerSecond
 * @param
 * @return
 * @note
 */
void initSystem(uint32_t ticksPerSecond)
{//
	//SystemInit();
	
#ifdef USE_DELAY	
	SysTick_Config(SystemCoreClock /ticksPerSecond);
#endif

#ifdef USE_UCOS	
	SysTick_Config(SystemCoreClock /OS_TICKS_PER_SEC);
#endif
	
	
#ifdef USE_FREERTOS
	SysTick_Config(SystemCoreClock /configTICK_RATE_HZ);
#endif	
	
}




#if 1

#pragma impourt (__use_no_semihosting)


struct __FILE
{
	int handle;
};



FILE __stdout;



void _sys_exit(int x)
{
	x  = x;
}


int fputc(int ch, FILE* f)
{
	sendByteByUsart(PRINT_USART, (uint8_t)ch);
	return ch;
}







#endif
